//
//  PopSelectView.m
//  WindRunner
//
//  Created by leeqb on 10/26/14.
//  Copyright (c) 2014 poweropt. All rights reserved.
//

#import "PopSelectView.h"

@implementation PopSelectView

- (id)initWithOptions:(NSArray *)options
{
    self = [super init];
    if(self) {
        self.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        
        _options = options;
    }
    return self;
}

- (void)show
{
    CGRect rect = CGRectZero;
    rect.origin.x = 0;
    rect.origin.y = 0;
    rect.size.width = SCREEN_WIDTH;
    rect.size.height = SCREEN_HEIGHT;
    UIView *blackView = [[UIView alloc] initWithFrame:rect];
    blackView.backgroundColor = [UIColor blackColor];
    blackView.alpha = 0.5;
    [self addSubview:blackView];
    
    rect.size.width = SCREEN_WIDTH - 20;
    rect.size.height = _options.count * 44;
    rect.origin.x = 10;
    rect.origin.y = (SCREEN_HEIGHT - rect.size.height) / 2;
    FMTableView *optionTable = [[FMTableView alloc] initWithFrame:rect];
    optionTable.delegate = self;
    optionTable.dataSource = self;
    [self addSubview:optionTable];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hide)];
    [blackView addGestureRecognizer:tapGesture];
    
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    [keyWindow addSubview:self];
}

- (void)hide
{
    [self removeFromSuperview];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _options.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"OptionSelectCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if(!cell) {
        cell = [[FMTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
        cell.backgroundColor = [UIColor whiteColor];
    }
    
    cell.textLabel.text = _options[indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    if(self.delegate && [self.delegate respondsToSelector:@selector(optionSelected:text:)]) {
        [self.delegate optionSelected:indexPath.row text:_options[indexPath.row]];
    }
    
    [self hide];
}

@end
